import { ref, reactive, onMounted, type Ref } from "vue";
import { message } from "@/utils/message";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { addDialog } from "@/components/ReDialog";
import editForm from "../form/index.vue";
import type { PaginationProps } from "@pureadmin/table";
import type { TriggerItem } from "./types";
import { cloneDeep } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/views/mytBase/hooks";

export function useTrigger(tableRef: Ref) {
  //表单数据
  const form = reactive<{
    triggerType: string;
    tenantId: string;
    status: string;
    triggerName: string;
    OrderBy: string;
  }>({
    triggerType: "",
    tenantId: "",
    status: "",
    triggerName: "",
    OrderBy: ""
  });

  const dataList = ref<TriggerItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  //分页大小
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const { switchStyle } = usePublicHooks();
  const switchLoadMap = ref({});

  // 表格列定义
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "触发器名称",
      prop: "triggerName",
      minWidth: 180
    },
    {
      label: "触发器类型",
      prop: "triggerType",
      minWidth: 130
    },
    {
      label: "参数数量",
      prop: "paramCount",
      minWidth: 90
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="活跃"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChangeStatus(scope as any)}
        />
      )
    },
    {
      label: "租户ID",
      prop: "tenantId",
      minWidth: 90
    },
    {
      label: "租户名称",
      prop: "tenantName",
      minWidth: 130
    },
    {
      label: "经销商ID",
      prop: "dealerId",
      minWidth: 90
    },
    {
      label: "经销商名称",
      prop: "dealerName",
      minWidth: 130
    },
    {
      label: "创建时间",
      prop: "createTime",
      minWidth: 180
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  // 切换状态
  function onChangeStatus({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "激活"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.triggerName
      }</strong>触发器吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        http
          .post(changeHttpLink("index.php/trigger/trigger/change_status"), {
            data: {
              triggerIds: [row.id],
              status: row.status
            }
          })
          .then((res: any) => {
            if (res.Success) {
              message(
                `已${row.status === 0 ? "停用" : "激活"}${row.triggerName}`,
                {
                  type: "success"
                }
              );
              onSearch();
            } else {
              row.status === 0 ? (row.status = 1) : (row.status = 0);
              message(res.Message, { type: "error" });
            }
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
          })
          .catch(err => {
            row.status === 0 ? (row.status = 1) : (row.status = 0);
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  // 测试触发器
  function handleTest(row) {
    http
      .post(changeHttpLink("index.php/trigger/trigger/test"), {
        data: {
          triggerId: row.id
        }
      })
      .then((res: any) => {
        if (res.Success) {
          message(`测试${row.triggerName}成功`, { type: "success" });
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  }

  // 删除触发器
  function handleDelete(row) {
    ElMessageBox.confirm(`是否确认删除触发器${row.triggerName}?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("index.php/trigger/trigger/delete"), {
            data: {
              triggerIds: [row.id]
            }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除触发器${row.triggerName}`, { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const triggerIds = curSelected.map(item => item.id);

    ElMessageBox.confirm(
      `是否确认删除选中的${curSelected.length}个触发器?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("index.php/trigger/trigger/delete"), {
            data: {
              triggerIds
            }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${curSelected.length}个触发器`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }

  // 搜索
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      triggerType: form.triggerType,
      tenantId: form.tenantId,
      status: form.status,
      triggerName: form.triggerName
    };

    http
      .post(changeHttpLink("/api/Trigger"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
          // 处理统计数据
          const stats = res.data.stats || {};
          totalCount.value = stats.total || 0;
          activeCount.value = stats.active || 0;
          typeCount.value = stats.typeCount || 0;
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  // 重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  // 打开对话框
  function openDialog(type = "新增", row = {}) {
    const result = addDialog({
      title: `${type}触发器`,
      props: {
        form: cloneDeep(row),
        type
      },
      width: "500px",
      draggable: true,
      contentRenderer: () => editForm
    });

    if (result && typeof result.then === "function") {
      result.then(() => {
        onSearch();
      });
    } else {
      onSearch();
    }
  }

  // 分页处理
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 选择变化
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }

  // 取消选择
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }

  // 统计数据
  const totalCount = ref(0);
  const activeCount = ref(0);
  const typeCount = ref(0);

  // 设备检测
  const deviceDetection = () => {
    return window.innerWidth < 1024;
  };

  // 初始加载
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    selectedNum,
    switchStyle,
    totalCount,
    activeCount,
    typeCount,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleTest,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel
  };
}
